﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using blackhouse.JavaScript.JQuery;
using System.ComponentModel;
using System.Collections;
using System.Text;
using blackhouse.BlackApart.Business.Calendar;
using blackhouse.Web.FasterFiles;
using blackhouse.BlackApart.Business;
using Resources;
using blackhouse.BlackApart.Business.Apartments;

namespace blackhouse.BlackApart.Web.Modules {
	public partial class Calendar : System.Web.UI.UserControl {

		#region Properies

		[Browsable(true)]
		[Category("Calendar")]
		[DefaultValue("MMMM yyyy")]
		public string SelectedMonthFormat {
			get;
			set;
		}

		[Browsable(true)]
		[Category("Calendar")]
		[DefaultValue("MMMM yy")]
		public string MonthFormat {
			get;
			set;
		}

		[Browsable(true)]
		[Category("Calendar")]
		[DefaultValue("ddd")]
		public string DayOfWeekFormat {
			get;
			set;
		}

		[Browsable(true)]
		[Category("Calendar")]
		public DateTime StartDate {
			get;
			set;
		}

		[Browsable(true)]
		[Category("Calendar")]
		[DefaultValue(6)]
		public int MonthsCount {
			get;
			set;
		}

		[Browsable(true)]
		[Category("Calendar")]
		[DefaultValue(false)]
		public bool AllowChangeGroup {
			get;
			set;
		}

		private IApartmentGroup group;

		private IApartmentGroup Group {
			get {
                if (this.group == null) {
                    DisplayApartmentTypeState state = DisplayApartmentTypeState.GetCurrentState();
                    if (state == null || state.ApartmentType == null) return null;
                    this.group = state.ApartmentType;
                }
                return group;
			}
		}

		private int GroupId {
			get {
				if (this.Group != null) return this.Group.Id;
				else return 0;
			}
		}

		#endregion

		#region Constructors

		public Calendar() {
			this.SelectedMonthFormat = "MMMM yyyy";
			this.MonthFormat = "MMMM yy";
			this.DayOfWeekFormat = "ddd";
			this.StartDate = DateTime.Now;
			this.MonthsCount = 6;
		}

		#endregion

		#region Control Methods

		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			this.PopulateControls();
			this.AddJS();
		}

		#endregion

		#region Methods

		private void ModifyCalendarForGroup(DisplayCalendar displayCalendar) {
			if (this.GroupId == 0) return;
            DateTime startDate = DisplayCalendar.GetStartDate(this.StartDate.Month, this.StartDate.Year);
            DateTime endDate = DisplayCalendar.GetEndDate(startDate);
            ApartmentTypeCalendar calendar = new ApartmentTypeCalendar(this.GroupId, startDate, endDate);
			displayCalendar.ApplyCalendar(calendar, this.GroupId);
		}

		private void PopulateControls() {
			ArrayList months = new ArrayList(this.MonthsCount);
			for (int xm = 0; xm < this.MonthsCount; xm++) {
				months.Add(this.StartDate.AddMonths(xm));
			}

			this.rptMonths.DataSource = months;
			this.rptMonths.DataBind();

			DateTime dayOfMonday = new DateTime(2011, 7, 11);
			string[] days = new string[7];
			for (int x = 0; x < 7; x++) {
				days[x] = dayOfMonday.AddDays(x).ToString(this.DayOfWeekFormat);
			}
			this.rptDayOfWeek.DataSource = days;
			this.rptDayOfWeek.DataBind();

			if (this.AllowChangeGroup) {
				this.pnlChangeGroup.Visible = true;
				this.rptGroups.DataSource = Factory.Instance().GetApartmentGroup().GetAllApartmentTypes();
				this.rptGroups.DataBind();
			}

			this.PopulateCalendar();
		}

		private void PopulateCalendar() {
			DisplayCalendar calendar = new DisplayCalendar(this.StartDate.Month, this.StartDate.Year);
			this.ModifyCalendarForGroup(calendar);
			StringBuilder builder = new StringBuilder();
			for (int xw = 1; xw <= calendar.Weeks; xw++) {
				builder.Append("<div class=\"cal-tr\">");
				for (int xdw = 0; xdw < 7; xdw++) {
					CalendarDay cDay = calendar.Days.FirstOrDefault(d => d.Week == xw && d.DayOfWeek == xdw);
					string css = "cal-td";
					string val = "";
					if (cDay != null) {
						css += " cal-td-type" + ((int)cDay.Type);
						val = cDay.Day + "/" + cDay.NextDay;
						if (cDay.Type == CalendarDayType.Free) {
							val = "<a title=\"" + this.Group.Name + "\" href=\"" + UrlUtils.LocalizeUrl("/pages/showreservationpopup.aspx")
								+ "?groupId=" + this.GroupId + "&search=" + SearchState.GetState(cDay.AssocDate, cDay.AssocDate.AddDays(1), 1) + "&iframe=true&width=600&height=480" + "\" popup=\"reservation\">"
								+ val + "</a>";

						}
					}
					else {
						css += " cal-td-empty";
					}
					builder.Append("<div class=\"" + css + "\">" + val + "</div>");
				}
				builder.Append("</div>");
			}
			lblCalcTd.Text = builder.ToString();
		}

		protected void rptMonths_ItemDataBound(object sender, RepeaterItemEventArgs e) {
			if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item) {
				Panel panel = e.Item.FindControl("pnlMonth") as Panel;
				Literal literal = e.Item.FindControl("lblMonth") as Literal;
				DateTime date = (DateTime)e.Item.DataItem;

				if (panel != null && literal != null) {
					if (date.Month == this.StartDate.Month) {
						literal.Text = date.ToString(this.SelectedMonthFormat);
						panel.CssClass = "red";
					}
					else
						literal.Text = date.ToString(this.MonthFormat);

					panel.Attributes.Add("selected-month", date.ToString(this.SelectedMonthFormat));
					panel.Attributes.Add("unselected-month", date.ToString(this.MonthFormat));
					panel.Attributes.Add("month", date.Month.ToString());
					panel.Attributes.Add("year", date.Year.ToString());
				}
			}
		}

		private void AddJS() {
			string jsCalendarUrl = "calendarUrl = '/Handlers/CalendarHandler.asmx/GetDays';";
			string jsCalendarData = @"
function calendarGetData(month, year) {" +
	"return \"{'month':\" + month + \",'year':\" + year + \"}\";" +
"}";

			if (this.GroupId > 0) {
				jsCalendarUrl = "calendarUrl = '/Handlers/CalendarHandler.asmx/GetDaysByGroup';";
				jsCalendarData = @"
function calendarGetData(month, year) {" +
		"return \"{'month':\" + month + \",'year':\" + year + \",'groupId':" + this.GroupId + "}\";" +
	"}";
			}

			if (this.AllowChangeGroup) {
				jsCalendarData = @"
var crnGroupId = " + this.GroupId + @";
function calendarGetData(month, year) {" +
		"return \"{'month':\" + month + \",'year':\" + year + \",'groupId':\" + crnGroupId + \"}\";" +
	"}";
			}

			JQueryLibraries jql = new JQueryLibraries();
			jql.IncludeFileBasedOnJQuery("blackhouse.BlackApart.Web.JavaScript.calendarBase.js,blackhouse.BlackApart.Web");
			if (this.AllowChangeGroup)
				jql.IncludeFileBasedOnJQuery("blackhouse.BlackApart.Web.JavaScript.calendarAllowChangeGroup.js,blackhouse.BlackApart.Web");
			FasterFilesProvider ffp = new FasterFilesProvider();
			ffp.AddAfterScript(jsCalendarUrl + "\r\n" + jsCalendarData);
		}

		#endregion

	}
}